package com.hae.shop.micoshopportalweb.controller.member;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.OtherUtils;
import com.hae.shop.member.model.reqDto.QQAutoLoginReqDto;
import com.hae.shop.member.model.respDto.UserLoginRespDto;
import com.hae.shop.micoshopportalweb.config.WXConfig;
import com.hae.shop.micoshopportalweb.controller.member.feign.MemberFeign;
import com.hae.shop.micoshopportalweb.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 微信登录相关
 */
@Controller
@Slf4j
public class WeiXinAuthoriController {

    @Autowired
    private MemberFeign memberFeign;

    @RequestMapping("wxloginx")
    public String wxloginx(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        request.setAttribute("avatarURL100", null);
        session.setAttribute(Constants.LOGIN_QQ_OPENID, "test");return Constants.MB_WX_QQLOGIN;
    }

    /**
     * 调用wx开放接口获取token
     *
     * @param request
     * @return
     */
    @RequestMapping("/wxAuth")
    public String wxAuth(HttpServletRequest request) {
        try {
            return Constants.REDIRECT_INDEX + SnsAPI.connectOauth2Authorize(WXConfig.getValue("app_ID"),
                    WXConfig.getValue("redirect_URI"), true, "STATE"); //Constants.REDIRECT_INDEX +
        } catch (Exception e) {
            return Constants.ERROR_FTL;
        }
    }

    /**
     * wx登录回调
     *
     * @return
     */
    @RequestMapping("wxLoginBack")
    public String wxLoginBack(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        //获取code
        String code = request.getParameter("code");
        if(StringUtils.isEmpty(code)){
            return Constants.ERROR_FTL;
        }
        //获取accesstoken及openid
        SnsToken snsToken = SnsAPI.oauth2AccessToken(WXConfig.getValue("app_ID"), WXConfig.getValue("app_KEY"), code);
        if (StringUtils.isEmpty(snsToken.getAccess_token()) || StringUtils.isEmpty(snsToken.getOpenid())) {
            return Constants.ERROR_FTL;
        }
        // 使用wx_openid调用会员服务进行自动登录
        QQAutoLoginReqDto loginReqDto = new QQAutoLoginReqDto();
        loginReqDto.setQqOpenId(snsToken.getOpenid());
        loginReqDto.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
        loginReqDto.setDeviceInfor(OtherUtils.webBrowserInfo(request));
        Response<UserLoginRespDto> loginRespDtoResponse;
        try {
            loginRespDtoResponse = memberFeign.autoLoginByQQ(loginReqDto);
        } catch (Exception e) {
            log.error("系统内部异常", e);
            return Constants.ERROR_FTL;
        }
        // 登录不成功则返回错误页面
        if (!loginRespDtoResponse.isSuccess()) {
            log.error("系统内部异常", loginRespDtoResponse.getErrorMsg());
            return Constants.ERROR_FTL;
        }
        // 登录结果为空，跳转到用户绑定界面
        if (StringUtils.isEmpty(loginRespDtoResponse.getResult().getUserid())) {
            User user = SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(), "zh_CN",1);
            if (user == null) {
                return Constants.ERROR_FTL;
            }
            // 返回用户头像页面展示并将openId放入session以备登录
            request.setAttribute("avatarURL100", user.getHeadimgurl());
            session.setAttribute(Constants.LOGIN_WX_OPENID, user.getOpenid());
            return Constants.MB_WX_QQLOGIN;
        }
        // 登陆成功之后如何处理 保持会话信息 将token存入到cookie 里面 首页读取cookietoken 查询用户信息返回到页面展示
        request.setAttribute("member_id", loginRespDtoResponse.getResult().getUserid());
        CookieUtils.setCookie(request, response, Constants.LOGIN_TOKEN_COOKIENAME, loginRespDtoResponse.getResult().getToken());
        return Constants.INDEX_FTL;
    }

}
